<?php
/**
 * Cube PHP Framework
 * 
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * @author Dillen / Steffen
 */

namespace Library\Mvc;
 
/**
 * @class Library.Mvc.Bootstrap 
 * 
 * Library.Mvc.Bootstrap is the application bootstrap class, which runs your actual application.
 */
class Bootstrap
{
	/**
	 * Application
	 * 
	 * @property {Library.Application} application
	 * @var \Library\Application
	 */
	private $_application;
	
	/**
	 * Request
	 * 
	 * @property {Library.Mvc.Request} request
	 * @var \Library\Mvc\Request
	 */
	private $_request;
	
	/**
	 * Router
	 * 
	 * @property {Library.Mvc.Router} router
	 * @var \Library\Mvc\Router
	 */
	private $_router;
    
    protected $_config;
	
	/**
	 * Constructor
	 * 
	 * @method __construct
	 * @param {Library.Application} $application
	 */
	public function __construct(\Library\Application $application)
	{
		//Set error handler
		$error = new \Library\Error($application, $this);
		
        //Set the error handler as exception handler
		set_exception_handler(array($error, 'displayException'));
		
		$this->_application = $application;
        $this->_config = $application->getConfig();
		
		$this->_applicationDispatch();
	}
	
	/**
	 * Router dispatch event
	 * 
	 * @method _routerDispatch
	 * @private
	 */
	final private function _applicationDispatch()
	{
        $this->_request = new \Library\Mvc\Request();
        
		$this->__routerPreDispatch($this->_request);
        
        //Dispatch the router
		$this->_router = new \Library\Mvc\Router($this->_request);
		$this->_router->preDispatch();
		$this->_router->dispatch($this);
		
		$this->__routerDispatch($this->request, $this->router);
	}
	
	/**
	 * Application pre-init event
	 * 
	 * @method __applicationpreInit
	 */
	protected function __applicationPreInit()
	{
		
	}
	
	protected function __applicationInit()
	{
		
	}
	
	protected function __applicationError(\Exception $exception)
	{
		
	}
    
    protected function __layoutPrerender($layout)
    {
        
    }
	
	protected function __routerPredispatch(&$request)
	{
		
	}
	
	protected function __routerDispatch(&$request, &$router)
	{
		
	}
	
	/**
	 * Call a bootstrap event
	 * 
	 * @param String $event
	 * @param Array $args
	 * @method callEvent
	 */
	public function callEvent($event, $args)
	{
        if (!is_array($args))
        {
            $args = array($args);
        }
        
		return count($args) > 0 ? call_user_func_array(array($this, '__' . $event), $args) : $this->{'__' . $event}();
	}
}